<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
    <!-- 需要隐藏的项上使用属性  v-show="showSearch" -->

      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          style="width: 232px"
          v-model="queryParams.nickName"
          maxlength="30"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="城市" prop="areaId">
        <el-select v-model="queryParams.areaId" filterable clearable placeholder="请选择城市" style="width: 232px">
          <el-option
            v-for="dict in areaList"
            :key="dict.id"
            :label="dict.areaAddr"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="订单状态" prop="configType">
        <el-select v-model="queryParams.orderStatusArr" placeholder="全部" multiple clearable>
          <el-option
            v-for="dict in dict.type.order_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item class="search">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-content">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            icon="el-icon-circle-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['project:distributor:add']"
          >新增</el-button>
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      </el-row>

      <el-table
        v-loading="loading"
        :data="distributorList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="用户id"  align="center" prop="userId" width="180px" show-overflow-tooltip/>
        <el-table-column label="头像" align="center" prop="avatar" >
          <template slot-scope="scope">
            <div v-if="scope.row.avatar"><img :src="scope.row.avatar" style="width: 60px;height: 60px" loading="lazy"></div>
            <div v-else>暂无头像</div>
          </template>
        </el-table-column>
        <el-table-column label="昵称"  align="center" prop="nickName" show-overflow-tooltip/>
        <el-table-column label="城市"  align="center" prop="areaAddr" show-overflow-tooltip/>
        <el-table-column label="子用户数量"  align="center" prop="childCount" show-overflow-tooltip/>
        <el-table-column label="订单数量"  align="center" prop="orderCount" show-overflow-tooltip/>
        <el-table-column label="注册时间"  align="center" prop="registerTime" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="小程序二维码" align="center" prop="wxCode">
          <template slot-scope="scope">
            <img
              v-if="scope.row.wxCode"
              :src="'data:image/png;base64,' + scope.row.wxCode"
              alt="二维码"
              style="width: 60px; height: 60px;"
              loading="lazy"
              @click="previewImage('data:image/png;base64,' + scope.row.wxCode)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240" fixed="right">
          <template slot-scope="scope">
            <!-- icon 详情：el-icon-view 修改：el-icon-edit 删除：el-icon-delete 审批、同意等: el-icon-s-check 新增：el-icon-plus 其他图标参考：https://element.eleme.cn/#/zh-CN/component/icon  -->
            <div style="text-align:right">
              <el-button
                v-hasPermi="['project:distributor:view']"
                size="mini"
                icon="el-icon-view"
                @click="handleView(scope.row.userId)"
              >查看成员</el-button>
              <el-button
                v-hasPermi="['project:distributor:remove']"
                size="mini"
                class="btn-delete"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >取消分销</el-button>
              <el-button
                v-hasPermi="['project:distributor:edit']"
                size="mini"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row, 'edit')"
              >修改</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加、查看、修改分销员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="openStatus === 'view'">
        <el-form-item label="头像" prop="avatar">
          <img :src="form.avatar" style="width: 100px;height: 100px" loading="lazy">
        </el-form-item>
        <el-form-item label="用户" prop="userId">
          <el-select
            :disabled="openStatus === 'edit'"
            v-model="form.userId"
            filterable
            clearable
            remote
            :remote-method="debouncedRemoteMethod"
            placeholder="请选择用户"
            style="width:100%"
            @change="changeUser"
            :reserve-keyword="true">
            <el-option
              v-for="dict in userList"
              :key="dict.userId"
              :label="dict.nickName"
              :value="dict.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间" prop="registerTime">
          <el-date-picker
            disabled
            clearable
            style="width:100%"
            v-model="form.registerTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择注册时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属城市" prop="areaId">
          <el-select v-model="form.areaId" filterable clearable placeholder="请选择城市" style="width:100%" @change="changeArea">
            <el-option
              v-for="dict in areaList"
              :key="dict.id"
              :label="dict.areaAddr"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="openStatus !== 'view'" :loading="buttonLoading" type="primary" size="mini" @click="submitForm">确 定</el-button>
        <el-button :loading="buttonLoading" @click="cancel" size="mini">{{ openStatus === 'view' ? '关 闭' : '取 消' }}</el-button>
      </div>
    </el-dialog>
    <!-- 查看成员 -->
    <el-dialog title="查看成员" :visible.sync="openMember" width="70%" append-to-body :close-on-click-modal="false">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            icon="el-icon-upload2"
            size="mini"
            @click="handleExport"
            v-hasPermi="['project:distributor:export']"
          >导出</el-button>
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      </el-row>
      <el-table
        v-loading="loading"
        :data="childList"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="用户id"  align="center" prop="userId" show-overflow-tooltip/>
        <el-table-column label="用户昵称"  align="center" prop="nickName" show-overflow-tooltip/>
        <el-table-column label="头像" align="center" prop="avatar" >
          <template slot-scope="scope">
            <div v-if="scope.row.avatar"><img :src="scope.row.avatar" style="width: 40px;height: 40px" loading="lazy"></div>
            <div v-else>暂无头像</div>
          </template>
        </el-table-column>
        <el-table-column label="商品名"  align="center" prop="productTitles" show-overflow-tooltip/>
        <el-table-column label="订单金额"  align="center" prop="realPrice" show-overflow-tooltip/>
        <el-table-column label="订单号"  align="center" prop="orderNo" show-overflow-tooltip/>
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="85px" fixed="right">-->
<!--          <template slot-scope="scope">-->
<!--            &lt;!&ndash; icon 详情：el-icon-view 修改：el-icon-edit 删除：el-icon-delete 审批、同意等: el-icon-s-check 新增：el-icon-plus 其他图标参考：https://element.eleme.cn/#/zh-CN/component/icon  &ndash;&gt;-->
<!--            <div style="text-align:right">-->
<!--              <el-button-->
<!--                size="mini"-->
<!--                class="btn-delete"-->
<!--                icon="el-icon-delete"-->
<!--                @click="handleDeleteUser(scope.row)"-->
<!--              >删除</el-button>-->
<!--            </div>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <pagination
        v-show="childTotal>0"
        :total="childTotal"
        :page.sync="queryChildParams.pageNum"
        :limit.sync="queryChildParams.pageSize"
        @pagination="getChildList"
      />
    </el-dialog>
    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="imagePreviewVisible" width="500px" append-to-body>
      <img :src="previewImageUrl" style="width: 100%; height: auto;" />
    </el-dialog>
  </div>
</template>

<script>
import { listDistributor, getDistributor, delDistributor, addDistributor, updateDistributor } from "@/api/distributor";
import {listArea} from "@/api/area";
import {listUser} from "@/api/system/user";
import {delChildOrder, listChild} from "@/api/order";

export default {
  name: "Distributor",
  dicts: ['sys_normal_disable', 'order_state'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 子用户总条数
      childTotal: 0,
      // 分销员表格数据
      distributorList: [],
      // 城市列表
      areaList: [],
      // 人员列表
      userList: [],
      // 自用户列表
      childList: [],
      // 图片预览相关
      imagePreviewVisible: false,
      previewImageUrl: "",
      // 分销员id
      distributorUserId: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看成员弹出层
      openMember: false,
      userSearchTimer: null,
      // 显示弹状态 edit view
      openStatus: 'view',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        areaId: undefined,
        orderStatusArr: []
      },
      // 查询子用户参数
      queryChildParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        areaId: [
          { required: true, message: "城市不能为空", trigger: "blur" }
        ],
        registerTime: [
          { required: true, message: "注册时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getAreaList();
  },
  methods: {
    /** 查询分销员列表 */
    getList() {
      this.loading = true;
      listDistributor(this.queryParams).then(response => {
        this.distributorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询城市列表 */
    getAreaList() {
      this.loading = true;
      listArea().then(response => {
        this.areaList = response.rows;
        this.loading = false;
      })
    },
    /** 查询人员列表 */
    getUserList(query) {
      this.loading = true;
      listUser(query).then(response => {
        this.userList = response.rows;
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,
        nickName: undefined,
        avatar: undefined,
        areaId: undefined,
        area: undefined,
        areaAddr: undefined,
        registerTime: undefined,
        wxCode: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        tenantId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.orderStatusArr = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getUserList();
      this.openStatus = 'add';
      this.open = true;
      this.title = "添加分销员";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.loading = true;
      this.openStatus = type;
      this.reset();
      const id = row.id || this.ids
      getDistributor(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = type === 'view' ? '查看分销员' : '修改分销员';
      });
    },
    /** 查看成员 */
    handleView(userId) {
      this.distributorUserId = userId;
      this.loading = true;
      this.getChildList();
      this.openMember = true;
    },
    /** 查询子用户 */
    getChildList() {
      if (this.distributorUserId) {
        this.queryChildParams.userId = this.distributorUserId;
        this.queryChildParams.orderStatusArr = this.queryParams.orderStatusArr;
        listChild(this.queryChildParams).then(response => {
          this.loading = false;
          this.childList = response.rows;
          this.childTotal = response.total;
        });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryChildParams.userId = this.distributorUserId;
      this.download('project/order/exportChild', {
        ...this.queryChildParams
      }, `子用户_${new Date().getTime()}.xlsx`)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateDistributor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addDistributor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认取消分销员id为"' + ids + '"的分销资格？').then(() => {
        this.loading = true;
        return delDistributor(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 删除成员按钮操作 */
    handleDeleteUser(row) {
      this.$modal.confirm('是否确认删除id为"' + row.userId + '"的用户？').then(() => {
        this.loading = true;
        return delChildOrder(row.userId);
      }).then(() => {
        this.loading = false;
        this.getChildList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 切换城市 */
    changeArea(areaId) {
      if (areaId) {
        const area = this.areaList.find(e => e.id === areaId);
        this.form.area = area.area;
        this.form.areaAddr = area.areaAddr;
      } else {
        this.form.area = undefined;
        this.form.areaAddr = undefined;
      }
    },
    /** 防抖远程搜索方法 */
    debouncedRemoteMethod(query) {
      // 清除之前的定时器
      if (this.userSearchTimer) {
        clearTimeout(this.userSearchTimer);
      }

      // 设置新的定时器，延迟300ms执行搜索
      this.userSearchTimer = setTimeout(() => {
        this.remoteMethod(query);
      }, 300);
    },
    /** 查询用户列表 */
    remoteMethod(nickName) {
      // 如果输入为空，清空用户列表
      if (!nickName) {
        this.userList = [];
        return;
      }
      this.getUserList({nickName});
    },
    /** 切换用户 */
    changeUser(userId) {
      if (userId) {
        const user = this.userList.find(e => e.userId === userId);
        this.form.nickName = user.nickName;
        this.form.avatar = user.avatar;
        this.form.registerTime = user.createTime;
      } else {
        this.form.nickName = undefined;
        this.form.avatar = undefined;
        this.form.registerTime = undefined;
        this.getUserList();
      }
    },
    /** 图片预览 */
    previewImage(url) {
      this.previewImageUrl = url;
      this.imagePreviewVisible = true;
    }
  }
};
</script>
<style lang="scss" scoped>
.table-fixed {
  ::v-deep .el-table__fixed-right {
    height: 100% !important; //设置高优先，以覆盖内联样式
  }
  ::v-deep .el-table__fixed {
    height: 100% !important; //设置高优先，以覆盖内联样式
  }
}
</style>
